package tree;

import offer.TreeNode;

import java.util.*;

public class leetCode297_Coder {
   String SEP = ",";
   String NULL = "#";
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
      if(root == null) return null;
      StringBuilder stringBuilder = new StringBuilder();
      serialize(root,stringBuilder);
      return stringBuilder.toString();
    }

    public void serialize(TreeNode root,StringBuilder stringBuilder){
        if(root == null){
            stringBuilder.append(NULL).append(SEP);
            return;
        }
        stringBuilder.append(root.val).append(SEP);
        serialize(root.left,stringBuilder);
        serialize(root.right,stringBuilder);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data == null) return null;
        String[] split = data.split(SEP);
        List<String> datas = new ArrayList<>(Arrays.asList(split));
        return deserialize(datas);
    }

    public TreeNode deserialize(List<String> data){
        if(data == null || data.size() == 0) return null;
        String remove = data.remove(0);
        if(remove.equals(NULL)){
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(remove));
        root.left = deserialize(data);
        root.right = deserialize(data);
        return root;
    }

}
